import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';

import * as Util from '../common/Util';
import { pageSize } from '../config/Common';

import {
  TabbedArea,
  TabPane
} from 'react-bootstrap';

import { message as MessageConfig } from '../config/Common';
import { product as ProductConfig } from '../config/Common';
import * as ProductActions from '../actions/ProductActions';
import * as MessageActions from '../actions/MessageActions';
import * as UserActions from '../actions/UserActions';
import * as RecommendActions from '../actions/RecommendActions';
import Pager from '../components/Pager';
import Container from '../components/Container';
import Message from '../components/Message';
import DialogCommon from '../components/DialogCommon';
import DialogAlert from '../components/dialog/DialogAlert';

class MessageApp extends React.Component {

  constructor () {
    super();  

    this.state = {
       dialogVisiable : false,
       dialogTitle : "",
       dialogContent : "",
       dialogButton : null,
       selectedTabKey : 2,
    }; 

    this.allPageIndex = 1;
    this.viewPageIndex = 1;
  }
  
  fetchAllMessageData (){
    let pIndex = this.allPageIndex;
    let dataParam = {
        start : pIndex, 
        limit : pageSize
    };
    this.props.messageAction.fetchMessage(dataParam);
  }

  fetchViewMessageData (){
    let pIndex = this.viewPageIndex;
    let dataParam = {
        start : pIndex, 
        limit : pageSize
    };
    this.props.messageAction.fetchViewMessage(dataParam);
  }

  componentDidMount(){
    let { product, message, messageAction, productAction } = this.props;
    
    this.fetchViewMessageData();
    
    //没有找到好的方法，暂时就用定时器的方式
    let timer = setInterval(function(){
      let { viewmessage_status = 0 } = this.props.message;
      if (viewmessage_status === 1) {
        clearInterval(timer);
        this.fetchAllMessageData();
      }
    }.bind(this), 100);
    
    if (product.product_status !== 1) {
      let dataParam = {
          start : this.pageIndex, 
          limit : 100,
          bossStatus : ProductConfig.productStatus.all,
          bossType: ProductConfig.productType.all
      };
      productAction.fetchProduct(dataParam);
    }
  }

  getAllPageEnabled(allMessage){
    let allPageEnabled = false;
    let pageTotalCount = (this.allPageIndex) * pageSize;
    if(allMessage && allMessage.length >= pageTotalCount){
      allPageEnabled = true;
    }
    return allPageEnabled;
  }

  getViewPageEnabled(viewMessage){
    let viewPageEnabled = false;
    let pageTotalCount = (this.viewPageIndex) * pageSize;
    if(viewMessage && viewMessage.length >= pageTotalCount){
      viewPageEnabled = true;
    }
    return viewPageEnabled;
  }

  onAllPageClick(){
    let pIndex = (this.allPageIndex + 1);
    this.allPageIndex = pIndex;

    this.fetchAllMessageData();
  }

  onViewPageClick(){
    let pIndex = (this.viewPageIndex + 1);
    this.viewPageIndex = pIndex;
    
    this.fetchViewMessageData();
  }

  formatMessage(){

    let { message } = this.props;

    let { allmessage, viewmessage } = message;

    if (allmessage && allmessage.length) {
      //按时间排序
      allmessage.sort(function(a,b){
        var time_a = (a.createdate || a.createtime),
            time_b = (b.createdate || b.createtime);

        time_a = Util.DateFormater(time_a, "yyyyMMddhhmmss");
        time_b = Util.DateFormater(time_b, "yyyyMMddhhmmss");

        return time_b - time_a;
      });
    }
    if (viewmessage && viewmessage.length) {
      //按时间排序
      viewmessage.sort(function(a,b){
        var time_a = (a.createdate || a.createtime),
            time_b = (b.createdate || b.createtime);

        time_a = Util.DateFormater(time_a, "yyyyMMddhhmmss");
        time_b = Util.DateFormater(time_b, "yyyyMMddhhmmss");

        return time_b - time_a;
      });
    }

    allmessage = allmessage.slice(0, this.allPageIndex * pageSize);
    viewmessage = viewmessage.slice(0, this.viewPageIndex * pageSize);
    
    return { allmessage, viewmessage };
  }

  componentDidUpdate(){
    let { product, message, history, messageAction} = this.props;
    let { product_sign_status = 0, product_unsign_status = 0, message:product_message = "", pid="" } = product;

    product.product_unsign_status = 0;
    product.product_sign_status = 0;
    
    if (product_sign_status === -1 || product_unsign_status === -1) {
        let dialogHeader = `系统提示`;
        let dialogContent  = <DialogAlert message={product_message}/>
        this.setState({
          dialogContent : dialogContent,
          dialogVisiable : true,
          dialogTitle : dialogHeader,
          dialogButton : [{
             text : "确定",
             style : "default"
          }]
        });

    }else if(product_sign_status === 1 || product_unsign_status === 1 ){

        let productStatus  = 0;
        if (product_sign_status === 1) {
            productStatus = ProductConfig.productStatus.hasSign;
        } 
        if (product_unsign_status === 1) {
            productStatus = ProductConfig.productStatus.noSign;
        }
        messageAction.updateMessageProduct(pid, productStatus);

        this.props.userAction.fetchUser();
    }
    
    let { message_confirm_status, message:message_mes } = message;
    if (message_confirm_status === -1) {
        let dialogHeader = `系统提示`;
        let dialogContent  = <DialogAlert message={message_mes}/>;
        let dialogButton = [{
          text:"知道了",
          style : "default"
        }];
        if (message_mes.indexOf("充值")>0) {
          dialogButton = [{
             text : "去充值",
             style : "primary",
             callback : function(){
                this.handleDialogHide();
                history.pushState(null, "/Recharge");
             }.bind(this)
          },{
            text : "取消",
            style : "default"
          }];
        }

        this.setState({
          dialogContent : dialogContent,
          dialogVisiable : true,
          dialogTitle : dialogHeader,
          dialogButton : dialogButton
        });
    }

    message.message_confirm_status = 0;
  }

  componentWillUnmount(){
    //清除消息数量
    this.props.messageAction.resetMessageCount();
    //复位消息
    //this.props.messageAction.resetMessage();
  }

  handleDialogHide(){
    this.setState({
       dialogVisiable : false
    });
  }

  handleTabSelect(index){
    this.setState({
      selectedTabKey : index
    });
  }
  
  render() {

    let { messageAction, productAction,  messageSysAction, message, messagesys, product, user, history } = this.props;

    let { allmessage, viewmessage } = this.formatMessage();

    let allPageEnabled = this.getAllPageEnabled(allmessage);
    let viewPageEnabled = this.getViewPageEnabled(viewmessage);

    let isGoBack = "Product";
    
    return (
          <Container 
              isGoBack={ isGoBack } 
              isHeader={ true } 
              isFooter={ false } 
              footerIndex={0} 
              headerTitle={"消息"}>

               <div className="product-container">
                  <TabbedArea activeKey={this.state.selectedTabKey} onSelect={ this.handleTabSelect.bind(this) }>
                    <TabPane eventKey={1} tab="所有消息">
                      {
                        message.message_status === 0 && allmessage.length === 0 ?
                        <div className="text-center padding-lg">
                          { message.message }
                        </div> 
                        :
                        allmessage.length > 0 ?
                        <Message 
                          messages = { allmessage } 
                          products = { product }
                          user = { user }
                          history = { history }
                          type = { MessageConfig.messageStatus.noSign } 
                          productAction = { productAction }
                          messageAction={ messageAction }/>
                        :
                        <div className="text-center padding-lg">
                          暂无消息记录
                        </div>  
                      }
                      {
                        allPageEnabled || allmessage.length > 0 ?
                        <Pager 
                          onPageClick = {this.onAllPageClick.bind(this)} 
                          enabled = { allPageEnabled } 
                          status = { message.message_status }>
                          点击加载更多
                        </Pager>
                        : null
                      }
                    </TabPane>

                    <TabPane eventKey={2} tab="已关注">
                      {
                        message.viewmessage_status === 0 && viewmessage.length === 0?
                        <div className="text-center padding-lg">
                          { message.message }
                        </div> 
                        :
                        viewmessage.length > 0 ?
                        <Message 
                          messages = { viewmessage } 
                          products = { product }
                          user = { user }
                          history = { history }
                          type = { MessageConfig.messageStatus.hasSign } 
                          productAction = { productAction }
                          messageAction={ messageAction }/>
                        :
                        <div className="text-center padding-lg">
                          暂无消息记录
                        </div>  
                      }
                      {
                        viewPageEnabled || viewmessage.length > 0 ?
                        <Pager 
                          onPageClick = {this.onViewPageClick.bind(this)} 
                          enabled = {viewPageEnabled} 
                          status = { message.viewmessage_status}>
                          点击加载更多
                        </Pager>
                        : null
                      }
                    </TabPane>
                  </TabbedArea>
               </div>

               <DialogCommon 
                  title={ this.state.dialogTitle } 
                  content={ this.state.dialogContent } 
                  buttons = { this.state.dialogButton }
                  visiable={ this.state.dialogVisiable } 
                  onHide = { this.handleDialogHide.bind(this) }/>
          </Container>
    );
  }
}

export default connect(state => ({
    user : state.user,
    product : state.product,
    message: state.message,
    recommend : state.recommend
}), dispatch => ({
    messageAction: bindActionCreators(MessageActions, dispatch),
    productAction : bindActionCreators(ProductActions, dispatch),
    userAction : bindActionCreators(UserActions, dispatch),
    recommendAction : bindActionCreators(RecommendActions, dispatch)
}))(MessageApp);

